package Extra;

// TCPEchoServer 
// Received Message From User And send ok to client

import java.net.ServerSocket ;
import java.net.Socket ;
import java.io.IOException ;
import java.io.PrintWriter ;
import java.util.Scanner ;

public class TCPEchoServer
{
   private static final int PORT = 5000 ;
   private static ServerSocket serverSocket ;
   private static Socket socket ;
   
   public static void main (String args[])
   {
      try
      {
         serverSocket = new ServerSocket(PORT);
         System.out.println("********** Server Open Connnection **********");
      }
      catch ( IOException e)
      {
         System.out.println("Unable to Attach To Port !");
         System.exit(1);
      }
      
      while ( true )
         accessClient();
   }
   
   public static void accessClient()
   {
      try
      {
         socket = serverSocket.accept();
         
         Scanner input = new Scanner ( socket.getInputStream() ) ;
         PrintWriter output = new PrintWriter( socket.getOutputStream() , true );
         
         String msgIn , msgOut ;
         
         msgIn = input.nextLine();
         
         while ( ! msgIn.equals("CLOSE") )
         {
            System.out.println("Client > " + msgIn );
            
            msgOut = " OK " ;
            output.println(msgOut);
            
            msgIn = input.nextLine();
         }
         
      }
      catch ( IOException e)
      {   e.printStackTrace();   }
      
      finally
      {
         try
         {
            if ( socket != null )
               socket.close();
            
            System.out.println("Server Close Client Connection !");
         }
         catch ( IOException  e)
         {
            System.out.println("Cannot Disconnect Client !");
            System.exit(1);
         }
      }
   }
}